package com.cntcdt.api.db.dao;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.cntcdt.api.db.dao.base.CdtUserDaoBase;
import com.cntcdt.api.db.model.CdtUserModel;
import com.cntcdt.api.utils.EmojiEncodeUtils;
import com.cntcdt.api.utils.EncryUtil;
import com.cntcdt.api.utils.LogUtils;
import com.cntcdt.api.utils.ReflectUtils;
import com.coola.jutil.sql.DBEngine;
import com.coola.jutil.sql.DBFactory;

/**
 * 这是cdt_user的Dao实现类
 */
public class CdtUserDao extends CdtUserDaoBase {
	/**
	 * CdtUserDao对象
	 */
	private static CdtUserDao instance = new CdtUserDao();

	/**
	 * 默认构造方法
	 */
	private CdtUserDao() {
	}

	/**
	 * 获得对象实例
	 */
	public static CdtUserDao getInstance() {
		return instance;
	}

	/**
	 * 插入一条数据
	 * 
	 * @param model
	 *            UserModel对象
	 * @return 返回插入影响行数
	 */
	public int insert(CdtUserModel userModel) {
		String nickName = EmojiEncodeUtils.filter2CharUnicode(userModel.getNickName());

		DBEngine localEngine = DBFactory.getKeepConnDBEngine("main");
		// String sql = "INSERT INTO " + TABLE + "
		// (UserName,NickName,OrgHeadPic,HeadPic,Password,Resume,IsPrivacy,Phone,Address,IdCard,RegisterIp,Sex,UserType,FromPlaceId,UserStatus,RegisterTime,UpdateTime,BirthDay,Job,Specialty,Post,WantToKnow,LastLoginTime,Lng,Lat)
		// VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
		// Object[] paramObj =
		// {model.getUserName(),model.getNickName(),model.getOrgHeadPic(),model.getHeadPic(),model.getPassword(),model.getResume(),model.getIsPrivacy(),model.getPhone(),model.getAddress(),model.getIdCard(),model.getRegisterIp(),model.getSex(),model.getUserType(),model.getFromPlaceId(),model.getUserStatus(),model.getRegisterTime(),model.getUpdateTime(),model.getBirthDay(),model.getJob(),model.getSpecialty(),model.getPost(),model.getWantToKnow(),model.getLastLoginTime(),model.getLng(),model.getLat()};
		StringBuffer sql = new StringBuffer("INSERT INTO " + TABLE + " (");
		StringBuffer stmts = new StringBuffer(" values(");
		List<Object> sqlArgs = new ArrayList<Object>();
		Field[] superfields = userModel.getClass().getSuperclass().getDeclaredFields();
		// Field[] fields = userModel.getClass().getDeclaredFields();
		for (Field field : superfields) {
			if (field.getName().equals("serialVersionUID") || field.getName().equals("id")) {
				continue;
			}
			if (ReflectUtils.getter(userModel, field.getName()) != null) {
				sql.append(" " + field.getName() + ",");
				stmts.append("?,");
				if (field.getName().equals("nickName")) {

					sqlArgs.add(nickName);
				} else {

					sqlArgs.add(ReflectUtils.getter(userModel, field.getName()));
				}
			}
		}

		String sqlstr = sql.toString();
		sqlstr = sqlstr.substring(0, sqlstr.length() - 1);
		sqlstr = sqlstr + ")";

		String stmtstr = stmts.toString();
		stmtstr = stmtstr.substring(0, stmtstr.length() - 1);
		stmtstr = stmtstr + ")";

		LogUtils.log.info(sqlstr + stmtstr);

		Object[] paramObj = sqlArgs.toArray();
		int id = 0;
		try {
			String tSql = sqlstr + stmtstr;
			id = localEngine.executeUpdate(tSql, paramObj);
			ResultSet rs = localEngine.executeQuery("select last_insert_id() as id");
			if (rs.next()) {
				id = rs.getInt("id");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			localEngine.close();
		}
		return id;
	}

	/**
	 * 根据帐号密码查询
	 * 
	 * @param account
	 * @param password
	 * @return
	 */
	public CdtUserModel findByMobileAndPwd(String phone, String pwd) {
		CdtUserModel result = null;
		pwd = EncryUtil.encode(pwd);
		String sql = "select * from  " + TABLE + " where mobile=? and pwd=?";
		Object[] paramObjs = { phone, pwd };
		List<CdtUserModel> modelList = this.queryModelList(sql, paramObjs);
		if (modelList.size() > 0) {
			result = modelList.get(0);
		}
		return result;
	}

	/**
	 * 根据帐号密码查询
	 * 
	 * @param account
	 * @param password
	 * @return
	 */
	public CdtUserModel findByMobile(String phone) {
		CdtUserModel result = null;
		String sql = "select * from  " + TABLE + " where mobile=?";
		Object[] paramObjs = { phone };
		List<CdtUserModel> modelList = this.queryModelList(sql, paramObjs);
		if (modelList.size() > 0) {
			result = modelList.get(0);
		}
		return result;
	}

	/**
	 * 根据帐号密码查询
	 * 
	 * @param account
	 * @param password
	 * @return
	 */
	public CdtUserModel findByWXOpenId(String wxOpenId) {
		CdtUserModel result = null;
		String sql = "select * from  " + TABLE + " where wxOpenId=?";
		Object[] paramObjs = { wxOpenId };
		List<CdtUserModel> modelList = this.queryModelList(sql, paramObjs);
		if (modelList.size() > 0) {
			result = modelList.get(0);
		}
		return result;
	}

	/**
	 * 根据UNIONID 查询出账号
	 * 
	 * @param account
	 * @param password
	 * @return
	 */
	public CdtUserModel findByWXUnionId(String wxUnionid) {
		CdtUserModel result = null;
		String sql = "select * from  " + TABLE + " where wxUnionid=? and (wxUnionid is not null and wxUnionid<>'')";
		Object[] paramObjs = { wxUnionid };
		List<CdtUserModel> modelList = this.queryModelList(sql, paramObjs);
		if (modelList.size() > 0) {
			result = modelList.get(0);
		}
		return result;
	}

	/**
	 * 根据微信公众号的OPENID查询出账号
	 * 
	 * @param account
	 * @param password
	 * @return
	 */
	public CdtUserModel findByWxGZHOpenId(String wxOpenId) {
		CdtUserModel result = null;
		String sql = "select * from  " + TABLE + " where wxGZHOpenId=?";
		Object[] paramObjs = { wxOpenId };
		List<CdtUserModel> modelList = this.queryModelList(sql, paramObjs);
		if (modelList.size() > 0) {
			result = modelList.get(0);
		}
		return result;
	}

	/**
	 * 根据微信公众号的OPENID查询出账号
	 * 
	 * @param account
	 * @param password
	 * @return
	 */
	public CdtUserModel findByNumberAccount(Long NumberAccount) {
		CdtUserModel result = null;
		String sql = "select * from  " + TABLE + " where NumberAccount=?";
		Object[] paramObjs = { NumberAccount };
		List<CdtUserModel> modelList = this.queryModelList(sql, paramObjs);
		if (modelList.size() > 0) {
			result = modelList.get(0);
		}
		return result;
	}

	/**
	 * 更新操作，自动根据userModel中已经设置的字段进行更新 必须要设置userModel.id属性 和 其他任意一个属性
	 * 
	 * 返回更新结果
	 */
	public boolean updateAny(CdtUserModel userModel) {
		String nickName = EmojiEncodeUtils.filter2CharUnicode(userModel.getNickName());

		StringBuffer sql = new StringBuffer("update  " + TABLE + " set ");
		List<Object> sqlArgs = new ArrayList<Object>();
		Field[] superfields = userModel.getClass().getSuperclass().getDeclaredFields();
		// Field[] fields = userModel.getClass().getDeclaredFields();
		for (Field field : superfields) {
			if (field.getName().equals("serialVersionUID") || field.getName().equals("id")) {
				continue;
			}
			if (ReflectUtils.getter(userModel, field.getName()) != null) {
				sql.append(" " + field.getName() + "=? ,");
				// sqlArgs.add(ReflectUtils.getter(userModel, field.getName()));
				if (field.getName().equals("nickName")) {

					sqlArgs.add(nickName);
				} else {

					sqlArgs.add(ReflectUtils.getter(userModel, field.getName()));
				}

			}
		}

		String sqlstr = sql.toString();
		sqlstr = sqlstr.substring(0, sqlstr.length() - 1);
		sqlstr = sqlstr + " where id=?";
		sqlArgs.add(userModel.getId());
		LogUtils.log.info(sqlstr);
		LogUtils.log.info(sqlArgs.toString());

		Object[] paramObj = sqlArgs.toArray();
		try {
			return writeDBEngine.executeUpdate(sqlstr, paramObj) > 0;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 根据leancloud clientId查询用户
	 * 
	 * @param account
	 * @param password
	 * @return
	 */
	public CdtUserModel findByLcClientId(String lcClientId) {
		CdtUserModel result = null;
		String sql = "select * from  " + TABLE + " where leancloudClientId=?";
		Object[] paramObjs = { lcClientId };
		List<CdtUserModel> modelList = this.queryModelList(sql, paramObjs);
		if (modelList.size() > 0) {
			result = modelList.get(0);
		}
		return result;
	}

	/**
	 * 根据leancloud clientId查询用户
	 * 
	 * @param account
	 * @param password
	 * @return
	 */
	public List<CdtUserModel> findUserForRegistermTime() {
		String sql = "SELECT * FROM cdt_user WHERE registerTime < '2015-11-11 00:00:00' AND platform IS NOT NULL";
		Object[] paramObjs = {};
		List<CdtUserModel> modelList = this.queryModelList(sql, paramObjs);
		return modelList;
	}

	/**
	 * 通过用户id或账号获取用户信息
	 * 
	 * @param idOrAcccount
	 * @return
	 */
	public CdtUserModel findByIdOrNumberAccount(int idOrAcccount) {
		String sql = "select * from "+TABLE+" where id =? union select * from "+TABLE+" where numberAccount =?";
		Object[] paramObjs = { idOrAcccount, idOrAcccount };
		List<CdtUserModel> modelList = this.queryModelList(sql, paramObjs);
		if (modelList != null && modelList.size() > 0) {
			return modelList.get(0);
		}
		return null;
	}

	/**
	 * 根据id,numberAccount,mobile查询用户信息
	 * 
	 * @param userParams
	 * @return
	 */
	public CdtUserModel findByIdOrNumberAccountOrPhone(String userParams) {
		String sql = "select * from " + TABLE + " where id = ? union select * from " + TABLE
				+ " where numberAccount = ? union select * from " + TABLE + " where mobile = ?";
		Object[] paramObjs = { userParams, userParams, userParams };
		List<CdtUserModel> modelList = this.queryModelList(sql, paramObjs);
		if (modelList != null && modelList.size() > 0) {
			return modelList.get(0);
		} else {
			return null;
		}
	}
}
